package com.infra.micro.quartz.domain.core;

import com.alibaba.fastjson2.JSON;
import com.infra.micro.quartz.model.req.HttpJobHandlerReq;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component("httpJobHandler")
public class HttpJobHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpJobHandler.class);

    public String run(String params) throws Exception {
        LOGGER.info("Http执行器调度开始，参数params：{}", params);

        if (params == null || params.trim().length() == 0) {
            LOGGER.info("params[" + params + "] invalid.");
            return null;
        }

        HttpJobHandlerReq webReqParamsDTO = JSON.parseObject(params, HttpJobHandlerReq.class);

        String url = webReqParamsDTO.getUrl();
        if (StringUtils.isBlank(url)) {
            LOGGER.info("url[" + url + "] invalid.");
            return null;
        }

        String method = webReqParamsDTO.getMethod();
        if (StringUtils.isBlank(method) || !Arrays.asList("GET", "POST").contains(method.toUpperCase())) {
            LOGGER.info("method[" + method + "] invalid.");
            return null;
        }

        // http request web client
        return method.equalsIgnoreCase("post")
                ? WebClient.requestPostJson(url, webReqParamsDTO.getData()) :
                WebClient.requestGet(url, webReqParamsDTO.getData());
    }
}

